package com.bcxj.internalcommon.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.bcxj.internalcommon.constant.IdentityConstant;
import com.bcxj.internalcommon.dto.TokenResult;

/**
 * ClassName: JwtUtils
 * Package: com.bcxj.internalcommon.util
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/9/18 22:51
 * @Version 1.0
 * @Since 1.0
 */
public class JwtUtils {

    // 密匙
    private static final String SECRET = "bcxj123123@!@#!#";


    // token 需要存入phone
    private static final String JWT_KEY_PHONE = "phone";

    // 存入身份，如司机，乘客
    private static final String JWT_KEY_IDENTITY = "identity";

    // 为了确保token的不一样，还是建议加上时间戳，这个key只是为了 token的唯一性
    private static final String JWT_KEY_TIMESTAMP = "timestamp";

    // token类型
    private static final String JWT_TOKEN_TYPE = "tokenType";

    /**
     * 生成Tokem
     * @param phone 手机号，这里认为是唯一的
     * @param identity 身份
     * @return Token
     */
    public static String generatorToken(String phone, String identity, String tokenType) {

        // 获取时间以便设置token的过期时间

        JWTCreator.Builder builder = JWT.create();
        builder.withClaim(JWT_KEY_PHONE, phone);
        builder.withClaim(JWT_KEY_IDENTITY, identity);
        builder.withClaim(JWT_TOKEN_TYPE, tokenType);
        builder.withClaim(JWT_KEY_TIMESTAMP, System.currentTimeMillis());

        // 生成token
        String token = builder.sign(Algorithm.HMAC256(SECRET));

        return token;
    }


    /**
     *  解析token
     * @param token token
     * @return TokenResult
     */
    public static TokenResult parseToken(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        String name = verify.getClaim(JWT_KEY_PHONE).asString();
        String age = verify.getClaim(JWT_KEY_IDENTITY).asString();

        return new TokenResult(name, age);
    }


    public static TokenResult checkToken(String token) {
        TokenResult tokenResult = new TokenResult();

        try {
            tokenResult = parseToken(token);
        }catch (Exception e){

        }
        return tokenResult;
    }


    public static void main(String[] args) {
        String token = generatorToken("13546789023", IdentityConstant.PASSENGER_IDENTITY, "");


        System.out.println(token);
        TokenResult tokenResult = parseToken(token);


        //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZSI6IjEzNTQ2Nzg5MDIzIiwiaWRlbnRpdHkiOiIwIiwidGltZXN0YW1wIjoxNzI3MTg0MzkyNjE2fQ.LlCYTCxKjhU83OT6ZxaKGnBcN9h59KfZlsO9rtH3j_4
        //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZSI6IjEzNTQ2Nzg5MDIzIiwiaWRlbnRpdHkiOiIwIiwidGltZXN0YW1wIjoxNzI3MTg0NDEwMzY0fQ.M0RqNFy0KL0Lx-YilwbUZyYvik7tXmbZv8JDqiHpQds
        System.out.println(tokenResult);
    }
}
